# -*- coding: utf-8 -*-
import time
from threading import Thread

from pubsub import pub
from selenium.webdriver.common.by import By
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support import expected_conditions as ec

from zhi_dao import driver
from zhi_dao import driver_wait
from zhi_dao.zhidao_const import event_video_progress_done
from zhi_dao.zhidao_const import event_video_progress_updated
from zhi_dao.zhidao_const import event_question_done
from zhi_dao.zhidao_const import event_video_change_speed_rate
from zhi_dao.zhidao_const import event_video_safe_verify_shown
import zhi_dao.question.zhidao_topic_monitor as topic_monitor
from zhi_dao.ai.zhidao_img_location_reader import ZhiDaoImgLocationReader
from zhi_dao import driver_action


class ZhiDaoVideoPlayer:

    video: WebElement = None

    img_location_reader: ZhiDaoImgLocationReader

    def __init__(self):
        self.img_location_reader = ZhiDaoImgLocationReader()
        process_monitor_thread = Thread(target=self.monitor_progress, args=())
        process_monitor_thread.start()

        topic_monitor_thread = Thread(target=topic_monitor.monitor, args=())
        topic_monitor_thread.start()

        video_safe_verify_monitor_thread = Thread(target=self.monitor_verify_model, args=())
        video_safe_verify_monitor_thread.start()

        pub.subscribe(self.play_video, event_question_done)
        pub.subscribe(self.set_speed_rate, event_video_change_speed_rate)

    # 播放视频
    def play_video(self):
        self.video = driver.find_element(By.TAG_NAME, "video")
        video_ready: bool = False
        while not video_ready:
            ready_state = driver.execute_script("return arguments[0].readyState", self.video)
            video_ready = ready_state == 4
        # 视频总时长
        video_duration = driver.execute_script("return arguments[0].duration", self.video)
        # 视频当前播放位置
        video_current_time = driver.execute_script("return arguments[0].currentTime", self.video)
        if video_current_time == video_duration or video_duration - video_current_time < 1:
            driver.execute_script("arguments[0].currentTime=0", self.video)
        # self.set_speed_rate(1.5)

        driver.execute_script("arguments[0].play()", self.video)

    def set_speed_rate(self, rate: float):
        driver.execute_script("arguments[0].playbackRate=" + str(rate), self.video)

    def monitor_progress(self):
        while True:
            if self.video is not None:
                try:
                    # 视频总时长
                    video_duration = driver.execute_script("return arguments[0].duration", self.video)
                    # 视频当前播放位置
                    video_current_time = driver.execute_script("return arguments[0].currentTime", self.video)
                    progress = round(video_current_time / video_duration * 100, 2)
                    pub.sendMessage(event_video_progress_updated, progress=progress)
                    if progress == 100:
                        pub.sendMessage(event_video_progress_done)

                except Exception as e:
                    print(e)

            time.sleep(1)

    def monitor_verify_model(self):
        while True:
            try:
                verify_model = driver_wait.until(ec.presence_of_element_located((By.CSS_SELECTOR, ".yidun_popup--light.yidun_popup.yidun_popup--size-small")))
                # verify_model = driver.find_element(By.CSS_SELECTOR, ".yidun_popup--light.yidun_popup.yidun_popup--size-small")
                if verify_model is not None:
                    # 获取到安全验证弹窗，发送提示
                    pub.sendMessage(event_video_safe_verify_shown)
                    # AI识别
                    # 获取图片链接
                    driver_wait.until(ec.presence_of_element_located((By.XPATH, "//div[@class='yidun_tips__content']")))
                    driver_wait.until(ec.presence_of_element_located((By.XPATH, "//span[@class='yidun_tips__text yidun-fallback__tip']")))
                    driver_wait.until(ec.presence_of_element_located((By.XPATH, "//img[@class='yidun_bg-img']")))
                    while True:
                        # 获取验证码图片
                        safe_verify_bg_img = None
                        try:
                            safe_verify_bg_img = driver.find_element(By.XPATH, "//img[@class='yidun_bg-img']")
                        except Exception as e:
                            print(e)
                        if safe_verify_bg_img is None:
                            break
                        # 获取验证码图片链接
                        bg_img_url = safe_verify_bg_img.get_attribute("src")
                        if bg_img_url is None:
                            continue
                        # location = safe_verify_bg_img.location
                        # x_location = location['x']
                        # y_location = location['y']
                        # 获取提示词
                        tip_span = driver.find_element(By.XPATH, "//span[@class='yidun_tips__text yidun-fallback__tip']")
                        content = self.img_location_reader.read(url=bg_img_url, question=tip_span.text)
                        offset_list = content.split()
                        x_offset = int(offset_list[0]) * 320 / 1000 - 160
                        y_offset = int(offset_list[1]) * 160 / 1000 - 80
                        driver_action.move_to_element_with_offset(safe_verify_bg_img, x_offset, y_offset).click().perform()
            except Exception as eg:
                print(eg)
